"""
Contains various storage domain test cases.
"""
import unittest as ut

import basicVdsTest as vdst
from confUtils import Validate
import vdsClient as vdsc
from storageConnectionTestUtils import eStorageType, disconnectFromStorage, connectToStorage
from storageConnectionTestUtils import validateConnections, CONNECTIONS_OPTION_DEFAULT, limitTestToConnectionType
from storageDomainTestUtils import eDomainClass, generateDomainTargets, destroyDomainTargets
from testUtils import cleanVdsm
from agentUtils import connectAgent

__commonConfig__ = {
    "VdsUri1" : {"default" : "http://server:54321"},
    "Connections" : {"default" : CONNECTIONS_OPTION_DEFAULT, "validator" : validateConnections},
    "DomainClass1" : {"default" : "data", "validator" : eDomainClass.parse},
    "Domain1" : {"default" : "GUID, GUID", "validator" : Validate.list},
    "StorageType1": {"default" : "nfs", "validator" : eStorageType.parse},
}

class DomainTestCaseBase(vdst.BasicVDSTest):
    """
    Contains common factors shared by all the storage domain test cases.
    """
    #For convenience. I didn't put it in the base class because I didn't want to commit.
    mycfg = property(lambda self: self.cfg[self.__class__.__name__])
    @classmethod
    def getConfigTemplate(cls):
        return { cls.__name__ : __commonConfig__ }

    def setUp(self):
        #Setup client
        self.client = vdsc.VDSClient()
        self.client.setURI(self.mycfg["VdsUri1"])

        #Make sure env is clean
        resp = self.assertVdscOK(self.client.getConnectedStoragePoolsList())
        self.assertTrue(len(resp['poollist']) == 0, "VDSM is connected to a pool. Dirty env. Bailing out.")

        #Handle storage configuration
        connectToStorage(self.client, self.mycfg["Connections"])
        self.domainTarget1 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["Domain1"]])[0]

    def tearDown(self):
        #disconnect
        destroyDomainTargets(self.client, [self.domainTarget1])
        disconnectFromStorage(self.client, self.mycfg["Connections"])

class ExtendDomain(DomainTestCaseBase):
    #For convenience. I didn't put it in the base class because I didn't want to commit.
    mycfg = property(lambda self: self.cfg[self.__class__.__name__])
    @classmethod
    def getConfigTemplate(cls):
        return {cls.__name__ : {
            "VdsUri1" : {"default" : "http://server:54321"},
            "Connections" : {"default" : CONNECTIONS_OPTION_DEFAULT, "validator" : validateConnections},
            "StorageType1": {"default" : "nfs", "validator" : eStorageType.parse},
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "Pool1Key" : {"default" : "NFSKEY"},
            "PVs": {"validator" : Validate.list}
            }
        }

    def setUp(self):
        #Setup client
        self.client = vdsc.VDSClient()
        self.client.setURI(self.mycfg["VdsUri1"])

        limitTestToConnectionType([eStorageType.iscsi], self.mycfg["Connections"])

        if len(self.mycfg["PVs"]) <= 3:
            raise Exception("Not enough PVs 3 required")

        #Make sure env is clean
        resp = self.assertVdscOK(self.client.getConnectedStoragePoolsList())
        self.assertTrue(len(resp['poollist']) == 0, "VDSM is connected to a pool. Dirty env. Bailing out.")

        connectToStorage(self.client, self.mycfg["Connections"])

        self.splitAt = 2

        self.domainTarget1 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["PVs"][:self.splitAt]])[0]

        self.sdUUID1 = self.client.newUUID()
        self.spUUID = self.client.newUUID()

    def test(self):
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledum", self.domainTarget1, vdsc.DATA_CLASS
                )
            )

        self.assertVdscOK(
            self.client.createStoragePool(self.spUUID, "AAHAHAHHAHAHAHAHAHA", self.sdUUID1, [self.sdUUID1], 1)
            )

        self.assertVdscOK(
            self.client.connectStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )

        taskid = self.assertVdscOK(self.client.spmStart(self.spUUID, -1, -1, -1, False))['uuid']
        self.assertVdscTaskOK(self.client, taskid)

        self.assertVdscOK(self.client.extendStorageDomain(self.sdUUID1, self.spUUID, self.mycfg["PVs"][self.splitAt:]))

    def tearDown(self):
        cleanVdsm(self.client, self.mycfg["HostID1"], self.mycfg["Connections"])

class OverExtendDomain(DomainTestCaseBase):
    """
    Test that the limit on PV number per domain is enforced even when extending
    """
    #For convenience. I didn't put it in the base class because I didn't want to commit.
    mycfg = property(lambda self: self.cfg[self.__class__.__name__])
    @classmethod
    def getConfigTemplate(cls):
        return {cls.__name__ : {
            "VdsUri1" : {"default" : "http://server:54321"},
            "Connections" : {"default" : CONNECTIONS_OPTION_DEFAULT, "validator" : validateConnections},
            "StorageType1": {"default" : "nfs", "validator" : eStorageType.parse},
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "Pool1Key" : {"default" : "NFSKEY"},
            "PVs": {"validator" : Validate.list}
            }
        }

    def setUp(self):
        #Setup client
        self.client = vdsc.VDSClient()
        self.client.setURI(self.mycfg["VdsUri1"])

        limitTestToConnectionType([eStorageType.iscsi], self.mycfg["Connections"])

        if len(self.mycfg["PVs"]) <= 10:
            raise Exception("Not enough PVs 10 required")

        #Make sure env is clean
        resp = self.assertVdscOK(self.client.getConnectedStoragePoolsList())
        self.assertTrue(len(resp['poollist']) == 0, "VDSM is connected to a pool. Dirty env. Bailing out.")

        connectToStorage(self.client, self.mycfg["Connections"])

        self.splitAt = 4

        self.domainTarget1 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["PVs"][:self.splitAt]])[0]

        self.sdUUID1 = self.client.newUUID()
        self.spUUID = self.client.newUUID()

    def test(self):
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledum", self.domainTarget1, vdsc.DATA_CLASS
                )
            )

        self.assertVdscOK(
            self.client.createStoragePool(self.spUUID, "AAHAHAHHAHAHAHAHAHA", self.sdUUID1, [self.sdUUID1], 1)
            )

        self.assertVdscOK(
            self.client.connectStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )

        taskid = self.assertVdscOK(self.client.spmStart(self.spUUID, -1, -1, -1, False))['uuid']
        self.assertVdscTaskOK(self.client, taskid)

        self.assertVdscFail(self.client.extendStorageDomain(self.sdUUID1, self.spUUID, self.mycfg["PVs"][self.splitAt:]))

    def tearDown(self):
        cleanVdsm(self.client, self.mycfg["HostID1"], self.mycfg["Connections"])

class CreateDomainWithTooManyPVs(vdst.BasicVDSTest):
    """
    Test that the limit on PV number per domain is enforced
    """
    #For convenience. I didn't put it in the base class because I didn't want to commit.
    mycfg = property(lambda self: self.cfg[self.__class__.__name__])
    @classmethod
    def getConfigTemplate(cls):
        return {cls.__name__ : {
            "VdsUri1" : {"default" : "http://server:54321"},
            "Connections" : {"default" : CONNECTIONS_OPTION_DEFAULT, "validator" : validateConnections},
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "StorageType1": {"default" : "nfs", "validator" : eStorageType.parse},
            "PVs": {"validator" : Validate.list}
            }
        }

    def setUp(self):
        #Setup client
        self.client = vdsc.VDSClient()
        self.client.setURI(self.mycfg["VdsUri1"])

        limitTestToConnectionType([eStorageType.iscsi], self.mycfg["Connections"])

        if len(self.mycfg["PVs"]) <= 10:
            raise Exception("Not enough PVs 10 required")

        #Make sure env is clean
        resp = self.assertVdscOK(self.client.getConnectedStoragePoolsList())
        self.assertTrue(len(resp['poollist']) == 0, "VDSM is connected to a pool. Dirty env. Bailing out.")

        connectToStorage(self.client, self.mycfg["Connections"])
        self.domainTarget1 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["PVs"]])[0]

        self.sdUUID1 = self.client.newUUID()

    def test(self):
        self.assertVdscFail(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledum", self.domainTarget1, vdsc.DATA_CLASS
                )
            )

    def tearDown(self):
        cleanVdsm(self.client, self.mycfg["HostID1"], self.mycfg["Connections"])

class DeactivateLastDomainWithExportDomainConnected(DomainTestCaseBase):
    """
    Test that storage domain deactivation works even if there is an active export domain connected.
    """
    @classmethod
    def getConfigTemplate(cls):
        extraConfig = {
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "Domain2" : {"default" : "GUID, GUID", "validator" : Validate.list},
            "Pool1Key" : {"default" : "NFSKEY"},
            "StorageType2": {"default" : "nfs", "validator" : eStorageType.parse},
            "DomainClass2" : {"default" : "data", "validator" : eDomainClass.parse},
        }

        extraConfig.update(__commonConfig__)

        return { cls.__name__ : extraConfig }

    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID1 = self.client.newUUID()
        self.sdUUID2 = self.client.newUUID()
        self.spUUID = self.client.newUUID()

        self.domainTarget2 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["Domain2"]])[0]

        #Create tmp domains
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledee", self.domainTarget1, self.mycfg["DomainClass1"]
                )
            )
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType2"], self.sdUUID2,
                "Tweedledum", self.domainTarget2, vdsc.BACKUP_DOMAIN
                )
            )
        #Create tmp pool
        self.assertVdscOK(
            self.client.createStoragePool(self.spUUID, "Through the Looking Glass", self.sdUUID1, [self.sdUUID1, self.sdUUID2], 1)
            )

        self.assertVdscOK(
            self.client.connectStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )

        #start tmp spm
        taskid = self.assertVdscOK(self.client.spmStart(self.spUUID, -1, -1, -1, False))['uuid']
        self.assertVdscTaskOK(self.client, taskid)

        #Activate domains
        self.assertVdscOK(self.client.activateStorageDomain(self.sdUUID1, self.spUUID))
        self.assertVdscOK(self.client.activateStorageDomain(self.sdUUID2, self.spUUID))

    def test(self):
        self.assertVdscOK(
            self.client.deactivateStorageDomain(self.sdUUID1, self.spUUID,
                vdst.BLANK_UUID, 0)
            )

    def tearDown(self):
        self.assertVdscOK(
            self.client.deactivateStorageDomain(self.sdUUID2, self.spUUID,
                vdst.BLANK_UUID, 0)
            )
        self.assertVdscOK(
            self.client.destroyStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )
        self.assertVdscOK(
            self.client.formatStorageDomain(self.sdUUID2)
            )
        self.assertVdscOK(
            self.client.formatStorageDomain(self.sdUUID1)
            )

        destroyDomainTargets(self.client, [self.domainTarget2])
        DomainTestCaseBase.tearDown(self)

class DeactivateStorageDomain(DomainTestCaseBase):
    """
    Test that storage domain deactivation works.
    """
    @classmethod
    def getConfigTemplate(cls):
        extraConfig = {
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "Domain2" : {"default" : "GUID, GUID", "validator" : Validate.list},
            "Pool1Key" : {"default" : "NFSKEY"},
            "StorageType2": {"default" : "nfs", "validator" : eStorageType.parse},
            "DomainClass2" : {"default" : "data", "validator" : eDomainClass.parse},
        }

        extraConfig.update(__commonConfig__)

        return { cls.__name__ : extraConfig }

    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID1 = self.client.newUUID()
        self.sdUUID2 = self.client.newUUID()
        self.spUUID = self.client.newUUID()

        self.domainTarget2 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["Domain2"]])[0]

        #Create tmp domains
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledee", self.domainTarget1, self.mycfg["DomainClass1"]
                )
            )
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType2"], self.sdUUID2,
                "Tweedledum", self.domainTarget2, self.mycfg["DomainClass2"]
                )
            )
        #Create tmp pool
        self.assertVdscOK(
            self.client.createStoragePool(self.spUUID, "Through the Looking Glass", self.sdUUID1, [self.sdUUID1, self.sdUUID2], 1)
            )

        self.assertVdscOK(
            self.client.connectStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )

        #start tmp spm
        taskid = self.assertVdscOK(self.client.spmStart(self.spUUID, -1, -1, -1, False))['uuid']
        self.assertVdscTaskOK(self.client, taskid)

        #Activate domain
        self.assertVdscOK(self.client.activateStorageDomain(self.sdUUID2, self.spUUID))

    def test(self):
        self.assertVdscOK(
            self.client.deactivateStorageDomain(self.sdUUID2, self.spUUID,
                vdst.BLANK_UUID, 0)
            )

        self.assertVdscOK(self.client.getStorageDomainInfo(self.sdUUID2))

    def tearDown(self):
        self.assertVdscOK(
            self.client.destroyStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )
        self.assertVdscOK(
            self.client.formatStorageDomain(self.sdUUID2)
            )
        self.assertVdscOK(
            self.client.formatStorageDomain(self.sdUUID1)
            )

        destroyDomainTargets(self.client, [self.domainTarget2])
        DomainTestCaseBase.tearDown(self)


class StorageDomainWithSameUUIDs(DomainTestCaseBase):
    """
    Test for storage domains with same UUID.
    """
    @classmethod
    def getConfigTemplate(cls):
        extraConfig = {
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "Pool1Key" : {"default" : "NFSKEY"},
            "Domain2" : {"default" : "GUID, GUID", "validator" : Validate.list},
            "DomainClass2" : {"default" : "data", "validator" : eDomainClass.parse},
            "StorageType2": {"default" : "nfs", "validator" : eStorageType.parse},
        }

        extraConfig.update(__commonConfig__)

        return { cls.__name__ : extraConfig }

    def setUp(self):
        limitTestToConnectionType([eStorageType.nfs], self.mycfg["Connections"])
        self.agent = connectAgent(self.mycfg["VdsUri1"])

        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID1 = self.client.newUUID()
        self.sdUUID2 = self.client.newUUID()
        self.spUUID = self.client.newUUID()

        self.domainTarget2 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["Domain2"]])[0]

        #Create tmp domains
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledee", self.domainTarget1, self.mycfg["DomainClass1"]
                )
            )
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType2"], self.sdUUID2,
                "Tweedledum", self.domainTarget2, self.mycfg["DomainClass2"]
                )
            )
        #Create tmp pool
        self.assertVdscOK(
            self.client.createStoragePool(self.spUUID, "Through the Looking Glass", self.sdUUID1, [self.sdUUID1], 1)
            )

        self.assertVdscOK(
            self.client.connectStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )

        #start tmp spm
        taskid = self.assertVdscOK(self.client.spmStart(self.spUUID, -1, -1, -1, False))['uuid']
        self.assertVdscTaskOK(self.client, taskid)

        #find out connections
        for name, storageType, connection in self.mycfg["Connections"]:
            if name == 'nfs3':
                self.con3 = connection['connection']
            elif name == 'nfs2':
                self.con2 = connection['connection']

    def twoNewIdenticalDomains(self):
        self.agent.duplicateDomain(self.con2, self.con3)

        self.assertVdscOK(self.client.refreshStoragePool(self.spUUID, self.sdUUID1, 1))

        resp = self.assertVdscOK(
                self.client.getStorageDomainsList(self.spUUID)
            )

        uuidlist = resp['domlist']
        self.assertEquals(len(uuidlist), 1)

        for uuid in uuidlist:
            self.assertTrue(uuid in [self.sdUUID1])

        # Erase duplicated domain
        self.agent.eraseDomain(self.con2)
        self.agent.eraseDomain(self.con3)

    def oneNewIdenticalDomain(self):
        self.assertVdscOK(self.client.attachStorageDomain(self.sdUUID2, self.spUUID))
        self.assertVdscOK(self.client.activateStorageDomain(self.sdUUID2, self.spUUID))

        self.agent.duplicateDomain(self.con2, self.con3)

        self.assertVdscOK(self.client.refreshStoragePool(self.spUUID, self.sdUUID1, 1))

        resp = self.assertVdscOK(
                self.client.getStorageDomainsList()
            )

        uuidlist = resp['domlist']
        self.assertEquals(len(uuidlist), 2)

        for uuid in uuidlist:
            self.assertTrue(uuid in [self.sdUUID1, self.sdUUID2])
        # Erase duplicated domain
        self.agent.eraseDomain(self.con3)

    def tearDown(self):
        cleanVdsm(self.client, self.mycfg["HostID1"], self.mycfg["Connections"])

class ActivateStorageDomain(DomainTestCaseBase):
    """
    Test that storage domain activation works.
    """
    @classmethod
    def getConfigTemplate(cls):
        extraConfig = {
            "HostID1" : {"default" : 7, "validator" : Validate.int},
            "Pool1Key" : {"default" : "NFSKEY"},
            "Domain2" : {"default" : "GUID, GUID", "validator" : Validate.list},
            "DomainClass2" : {"default" : "data", "validator" : eDomainClass.parse},
            "StorageType2": {"default" : "nfs", "validator" : eStorageType.parse},
        }

        extraConfig.update(__commonConfig__)

        return { cls.__name__ : extraConfig }

    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID1 = self.client.newUUID()
        self.sdUUID2 = self.client.newUUID()
        self.spUUID = self.client.newUUID()

        self.domainTarget2 = generateDomainTargets(self.client, self.mycfg["Connections"], [self.mycfg["Domain2"]])[0]

        #Create tmp domains
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID1,
                "Tweedledee", self.domainTarget1, self.mycfg["DomainClass1"]
                )
            )
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType2"], self.sdUUID2,
                "Tweedledum", self.domainTarget2, self.mycfg["DomainClass2"]
                )
            )
        #Create tmp pool
        self.assertVdscOK(
            self.client.createStoragePool(self.spUUID, "Through the Looking Glass", self.sdUUID1, [self.sdUUID1, self.sdUUID2], 1)
            )

        self.assertVdscOK(
            self.client.connectStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )

        #start tmp spm
        taskid = self.assertVdscOK(self.client.spmStart(self.spUUID, -1, -1, -1, False))['uuid']
        self.assertVdscTaskOK(self.client, taskid)

    def test(self):
        self.assertVdscOK(self.client.activateStorageDomain(self.sdUUID2, self.spUUID))

        self.assertVdscOK(self.client.getStorageDomainInfo(self.sdUUID2))

    def tearDown(self):
        self.assertVdscOK(
            self.client.deactivateStorageDomain(self.sdUUID2, self.spUUID,
                vdst.BLANK_UUID, 0)
            )
        self.assertVdscOK(
            self.client.destroyStoragePool(self.spUUID, self.mycfg["HostID1"], self.mycfg["Pool1Key"])
            )
        self.assertVdscOK(
            self.client.formatStorageDomain(self.sdUUID2)
            )
        self.assertVdscOK(
            self.client.formatStorageDomain(self.sdUUID1)
            )

        destroyDomainTargets(self.client, [self.domainTarget2])
        DomainTestCaseBase.tearDown(self)

class FormatDomain(DomainTestCaseBase):
    """
    Tests deletion of a domain
    """
    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID = self.client.newUUID()

        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", self.domainTarget1, self.mycfg["DomainClass1"]
                )
            )

    def test(self):
        self.assertVdscOK(self.client.formatStorageDomain(self.sdUUID))

        self.assertVdscFail(self.client.getStorageDomainInfo(self.sdUUID))

class RemoveNonExistingDomain(DomainTestCaseBase):
    """
    Test the domain removal fails in various cases.
    """
    def test(self):
        self.assertVdscFail(self.client.formatStorageDomain(vdsc.VDSClient.newUUID()))

class SetDomainDescription(DomainTestCaseBase):
    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID = self.client.newUUID()

        #Create the first domain
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", self.domainTarget1, vdsc.DATA_CLASS
            )
        )

    def testGoodDescription(self):
        desc = "Ve Ze Lo Keif"
        self.assertVdscOK(
            self.client.setStorageDomainDescription(self.sdUUID, desc)
        )
        currentName = self.assertVdscOK(self.client.getStorageDomainInfo(self.sdUUID))['info']['name']
        self.assertEquals(currentName, desc)

    def testLongDescription(self):
        desc = "KICK ME" * 100
        self.assertVdscFail(
            self.client.setStorageDomainDescription(self.sdUUID, desc)
        )

    def tearDown(self):
        #Clean up my stub domain
        self.assertVdscOK(self.client.formatStorageDomain(self.sdUUID))

        DomainTestCaseBase.tearDown(self)

class CreateDomainWithExistingUuid(DomainTestCaseBase):
    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID = self.client.newUUID()

        #Create the first domain
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", self.domainTarget1, vdsc.DATA_CLASS
            )
        )

    def test(self):
        self.assertVdscFail(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", self.domainTarget1, self.mycfg["DomainClass1"]
            )
        )

    def tearDown(self):
        #Clean up my stub domain
        self.assertVdscOK(self.client.formatStorageDomain(self.sdUUID))

        DomainTestCaseBase.tearDown(self)

class FailCreateDomainTestCases(DomainTestCaseBase):
    """
    Tests that domain creation fails in various cases.
    """
    def setUp(self):
        DomainTestCaseBase.setUp(self)

        #Setup test variables
        self.sdUUID = self.client.newUUID()

    def testInvalidDomainClass(self):
        """
        Test that a domain creation fails if given an invalid nfs export
        """
        self.assertVdscFail(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", self.domainTarget1, 0
            )
        )

        self.assertVdscFail(self.client.getStorageDomainInfo(self.sdUUID))

    def testInvalidDomainTarget(self):
        """
        Test that a domain creation fails if given an invalid nfs export
        """
        self.assertVdscFail(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", "CRASH!! CRASH AND BURN!!", self.mycfg["DomainClass1"]
            )
        )

        self.assertVdscFail(self.client.getStorageDomainInfo(self.sdUUID))

    def testInvalidUuid(self):
        """
        Test that a domain creation fails if given an invalid UUID.
        """
        self.assertVdscFail(
            self.client.createStorageDomain(self.mycfg["StorageType1"], "INVALID!!!",
                "Storage Domain 1", self.domainTarget1, self.mycfg["DomainClass1"]
            )
        )

        self.assertVdscFail(self.client.getStorageDomainInfo(self.sdUUID))

class CreateDomain(DomainTestCaseBase):
    """
    Tests domain creation.
    """
    def setUp(self):
        self.agent = connectAgent(self.mycfg["VdsUri1"])

        DomainTestCaseBase.setUp(self)

        # Setup test variables
        self.sdUUID = self.client.newUUID()

    def tearDown(self):
        #Clean env
        self.assertVdscOK(self.client.formatStorageDomain(self.sdUUID))

        DomainTestCaseBase.tearDown(self)

    def test(self):
        self.assertVdscOK(
            self.client.createStorageDomain(self.mycfg["StorageType1"], self.sdUUID,
                "Storage Domain 1", self.domainTarget1, self.mycfg["DomainClass1"]
                )
            )

        self.assertVdscOK(self.client.getStorageDomainInfo(self.sdUUID))

    def lvmPreferredNames(self):
        # Change lvm.conf
        self.agent.changeLvmConf()
        # Clear LVM cache
        self.agent.rebuildLvmCache()

        self.test()

        # restore lvm.conf
        self.agent.changeLvmConf(True)
        # Clear LVM cache
        self.agent.rebuildLvmCache()

def suite():
    tests = {
        CreateDomain : ["test", "lvmPreferredNames"],
        FormatDomain : ["test"],
        RemoveNonExistingDomain : ["test"],
        CreateDomainWithExistingUuid : ["test"],
        FailCreateDomainTestCases : ["testInvalidUuid", "testInvalidDomainTarget", "testInvalidDomainClass"],
        ActivateStorageDomain : ["test"],
        DeactivateStorageDomain : ["test"],
        DeactivateLastDomainWithExportDomainConnected : ["test"],
        SetDomainDescription : ["testGoodDescription", "testLongDescription"],
        OverExtendDomain : ["test"],
        ExtendDomain : ["test"],
        StorageDomainWithSameUUIDs : ["oneNewIdenticalDomain", "twoNewIdenticalDomains"],
        CreateDomainWithTooManyPVs : ["test"]
    }

    resSuite = ut.TestSuite()
    for testcase, methods in tests.iteritems():
        resSuite.addTests(map(testcase, methods))

    return resSuite

validateConfig = lambda cfg : vdst.validateSuiteConfig(suite(), cfg)
